<?php
namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\SendSMS;
use Common\Library\Constant;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Library\CacheRedis;
use Home\Model\ConsumeHistoryModel;
use Think\Controller;
use Think\Exception;
use Think\Log;
use Home\Model\JPushModel;

class JPushController extends Controller
{

    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
            $this->ajaxReturn($ret);
        }
    }

    /****** 审批结果 ******/
    public function pushWaitingReview(){
        try{
            $consumeId = I('post.consume_id');
            $msgType = I('post.msg_type');
            if(!$consumeId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            //获取用户当前订单的状态
            $res = M('ConsumeHistory')->where(['id'=>$consumeId])->find();
            
            if(!$res){
                BusinessException::throwException(Constant::ORDER_ID_NOT_FOUNT);
            }
            if($res['type'] == Constant::PAY_TYPE_INSTALLMENT || $res['type'] == Constant::PAY_TYPE_NEXT_MONTH){
                if($res['down_payment']){
                    if($res['status'] != ConsumeHistoryModel::STATUS_DOWN_PAYMENT){
                        BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
                    }
                }else{
                    if($res['status'] != ConsumeHistoryModel::STATUS_REVIEWED){
                        BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
                    }
                }
            }else if($res['type'] == Constant::PAY_TYPE_WITHDRAWAL_APPLY){
                if($res['status'] != ConsumeHistoryModel::STATUS_CASH_REVIEWED){
                    BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
                }
            }else{
                if($res['status'] != ConsumeHistoryModel::STATUS_REVIEWED){
                    BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
                }
            }

            $msgContent = '';
            if($msgType == 1){
                $msgContent = "哇哦~~，买呗小妹给您送钱咯~~";
                $res = M('ConsumeHistory')->where(['id'=>$consumeId])->find();
                $res['consume_id'] = $res['id'];
                $data = D('ConsumeHistory')->getCurOrderStatus($res);
                if($data['status'] == ConsumeHistoryModel::STATUS_WAIT_TWO){
                    $data['status'] = ConsumeHistoryModel::STATUS_REVIEWED;
                }
            }else if($msgType == 2){
                $msgContent = "恭喜您，您在找钱花的申请已经通过审核了，马上有钱了～～";
                $customer = D('Customer')->has($res['customer_id']);
                //获取用户当前订单的状态
                $data['status'] = $res['status'];
                if($data['status'] == ConsumeHistoryModel::STATUS_REVIEW_FAILED || $data['status']== ConsumeHistoryModel::STATUS_TONDDUN_FAILED){
                    $data['reason'] = Constant::TIPS_ORDER_FAILED;
                }else if($data['status'] == ConsumeHistoryModel::STATUS_CASH_REVIEWED){
                    //$data['amount'] = $customer['balance_cash_amount'];
                    //上面那个注释的错了，应该给用户发本次审核通过的钱数，by deron
                    $data['amount'] = $res['amount'];
                }
                //写入通知缓存
                CacheRedis::setKey($res['customer_id'], Constant::PAY_TYPE_WITHDRAWAL_APPLY);
            }

            //获取用户的push_id
            $pushId = M('Customer')->where(['id'=>$res['customer_id']])->getField('push_id');
            Log::write("订单内容：".$res.", 用户的push_id=".$pushId.',sql='.M('Customer')->getLastSql(), Log::INFO);

            $res = D('JPush')->send_push($data, $msgType, $pushId, $msgContent);
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    /**
     * 订单待审核时各个环节的push推送
     */
    public function orderPush()
    {
        try{
            $customerId = I('post.customer_id');
            $msgType = I('post.msg_type');

            if(!$customerId || !$msgType){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //获取pushid和最后一个消息id值
            D('Customer')->has($customerId);
            $pushId = M('Customer')->where(['id'=>$customerId])->getField('push_id');
            $res = D('ConsumeHistory')->getConsumeListByCustomerId($customerId, 0, 1);

            if($pushId && $res[0]){
                $data['consume_id'] = $res[0]['consume_id'];
                $msgContent = "亲，订单有新进度咯！";
                D('JPush')->send_push($data, $msgType, $pushId, $msgContent);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch  (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /***** 通用push方法 *****/
    public function commonPush()
    {
        try{
            $customerId = I('post.customer_id');
            $msgType = I('post.msg_type');

            if(!$customerId || !$msgType){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //获取pushid和最后一个消息id值
            $customer = D('Customer')->has($customerId);
            $pushId = M('Customer')->where(['id'=>$customerId])->getField('push_id');

            //还款push
            $unit_name = '';
            if($pushId && ($msgType = JPushModel::MSG_TYPE_REPAY_OVER)){
                //获取产品列表
                $cash_conf = M('SysInstallmentPlan')->order('repay_times')->where(['publish'=>1, 'target'=>3])->select();
                if(!$cash_conf){
                    BusinessException::throwException(Constant::ERROR_RETURN_DATA);
                }
                foreach ($cash_conf as $k=>$v){
                    if ($k == $customer['credit_level']){
                        $msgContent = '亲，感谢您的良好信用，趣分期为您解锁了一款新产品，赶快试一试吧！';
                        $unit_name = $v['repay_unit'] == Constant::REPAY_DAY ? '日' : '月';
                        $data['borrow_time'] = $v['timer'].$unit_name;
                        break;
                    }
                }
            }
            if($unit_name){
                D('JPush')->send_push($data, $msgType, $pushId, $msgContent);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch  (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }
}